<template>
  <div class="configuredRule">
    <el-card shadow="hover" class="card-search">
      <el-row>
        <el-col :span="20">
          <div class="search_detail">
            <div class="search">
              <span class="span_name">班级名称：</span>
              <el-input v-model="state.params.realName" placeholder="请输入" clearable />
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
          <el-button type="danger" :icon="Delete" @click="reast">重置</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="hover" class="card-main">
      <el-button type="primary" :icon="CirclePlusFilled" @click="addmore">新增</el-button>
      <el-table :data="state.tableData" stripe style="width: 100%">
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column prop="className" label="班级名称" align="center" />
        <el-table-column prop="studentCount" label="班级人数" align="center" />
        <el-table-column prop="realName" label="上课时间" align="center">
          <template #default="scope">
            <span>{{ scope.row.classStartDate }}</span>
            <span>{{ scope.row.classEndDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="带课老师" show-overflow-tooltip align="center" />
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" @click="update(scope.row)">编辑</el-button>
            <el-button type="primary" @click="update(scope.row)">课表</el-button>
            <el-button type="danger" @click="Deletet(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background @current-change="changepage" layout="prev, pager, next" :total="state.totalPage" />
      </div>
    </el-card>
    <el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" title="班级管理" width="760px"
      :before-close="handleClose">
      <div class="inputa">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="班级名称：" prop="username">
            <el-input style="width: 430px" v-model="ruleForm.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="上课时长：" prop="mobile">
            <el-col :span="8">
              <el-form-item prop="date1">
                <el-date-picker v-model="ruleForm.date1" type="date" placeholder="请选择开始时间" />
              </el-form-item>
            </el-col>
            <!-- <el-col class="text-center" :span="1" style="text-align: center;width: 20px;"> -->
            <span style="text-align: center;width: 20px;">-</span>
            <!-- </el-col> -->
            <el-col :span="8">
              <el-form-item prop="date2">
                <el-date-picker v-model="ruleForm.date1" type="date" placeholder="请选择结束时间" />
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="选择教师" prop="region">
            <el-select multiple style="width: 430px" v-model="ruleForm.region" placeholder="请选择">
              <el-option v-for="item in state.options" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="班级人数：" prop="realName">
            <el-input-number v-model="ruleForm.realName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="选择学生" prop="region">
            <el-transfer v-model="value" :titles="['未选学生', '选中学生']" filterable :filter-method="filterMethod"
              filter-placeholder="请选择" :data="data" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog top="5vh" :close-on-click-modal="false" v-model="state.dialogVisibleBjkb" title="课表安排" width="60%"
      :before-close="handleClose">
      <div style="height: 70vh;">
        <el-calendar :model="'2024-1-10'" style="height: 100%;" ref="calendar" v-model="state.Calendar">
          <template #header="{ date }">
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-month')">
                上个月
              </el-button>
            </el-button-group>
            <span>{{ date }}</span>
            <el-button-group>
              <el-button size="small" @click="selectDate('today')">今天</el-button>
              <el-button size="small" @click="selectDate('next-month')">
                下个月
              </el-button>
            </el-button-group>
          </template>
          <template #date-cell="{ data }">
            <p @click="showDrawer(data)">
              {{ data.day.split('-').slice(1).join('-') }}
            </p>
          </template>
        </el-calendar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer v-model="state.drawer" title="" :with-header="false">
      <div class="drawer-content">
        <h3 style="text-align: center;">{{ state.choseCalendarValue }}</h3>
        <div>
          <div style="text-align: right;margin-bottom: 20px;">
            <el-button type="primary" circle @click="addPk">
              <el-icon>
                <Plus color="#fff" />
              </el-icon>
            </el-button>
          </div>
          <div v-for="(item, index) in state.pkArray" :key="index" class="blcok2">
            <div class="block3">
              <div class="span-txt1">课时长：</div>
              <el-time-picker :model="item.time" is-range range-separator="~" start-placeholder="开始时间"
                end-placeholder="结束时间" />
            </div>
            <div class="block3">
              <div class="span-txt1">选择教师：</div>
              <el-select :model="item.teacher" multiple placeholder="请选择" style="width: 240px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button size="small" class="button" type="primary" circle @click="reduce(index)" color="red">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch } from 'vue'
import { Delete, Search, CirclePlusFilled, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance();
const ruleFormRef = ref()
const state = reactive({
  dialogVisible: false,
  dialogVisibleBjkb: true,
  drawer: false,
  choseCalendarValue: '',//选择的日期日期
  options: [],
  name: '',
  time: '',
  tableData: [],
  page: 1,
  totalPage: 0,
  row: {},
  params: {
    monthStatus: '',
    realName: '',
    roleId: '',
    time: ['', ''],
    startDate: '',
    endDate: '',
  },
  pkArray: [
    { time: '', teacher: '' },
  ],
  Calendar: new Date()
})


const generateData = () => {
  const data = []
  const states = [
    'California',
    'Illinois',
    'Maryland',
    'Texas',
    'Florida',
    'Colorado',
    'Connecticut ',
  ]
  const initials = ['CA', 'IL', 'MD', 'TX', 'FL', 'CO', 'CT']
  states.forEach((city, index) => {
    data.push({
      label: city,
      key: index,
      initial: initials[index],
    })
  })
  return data
}

const data = ref(generateData())
const value = ref([])
const calendar = ref();
const selectDate = (val) => {
  calendar.value.selectDate(val);
};
const filterMethod = (query, item) => {
  return item.initial.toLowerCase().includes(query.toLowerCase())
}
//显示日历点击具体日期
const showDrawer = (data) => {
  console.log('cdscdscsdc', data);
  state.drawer = true
}
//关闭抽屉
const cancelClick = () => {
  state.drawer = false
}
//抽屉点击确认
function confirmClick() {
  ElMessageBox.confirm(`是否确认?`)
    .then(() => {
      state.drawer = false
    })
    .catch(() => {
      // catch error
    })
}
//添加排课时间和教师
const addPk = () => {
  state.pkArray.push({ time: '', teacher: '' })
}
//删除排课时间和教师
const reduce = (index) => {
  state.pkArray.splice(index, 1)
}
watch(
  () => state.Calendar,
  () => {
    console.log('cdsjbichdwioujfdjbgrejfbhrfve', state.Calendar);
    let date = new Date(state.Calendar);
    let year = date.getFullYear(); // 2019
    let month = date.getMonth() + 1; // 9
    let day = date.getDate(); // 13
    let hour = date.getHours(); // 15
    let minute = date.getMinutes(); // 37
    let second = date.getSeconds(); // 3
    state.choseCalendarValue = `${year}-${month}-${day}`
    let formatted = `${year}-${month}-${day} ${hour}:${minute}:${second}`; // "2019-9-13 15:37:3"
    console.log('cdsncdscvbkjvdfvdf', formatted);
    state.drawer = true
  }
)

const formSize = ref('default')
const ruleForm = reactive({
  username: '',
  realName: '',
  mobile: '',
  password: '',
  region: '',
  sation: true,
  status: 1,
  roleIdList: [],
})

const rules = reactive({
  username: [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  // password: [
  //     { required: true, message: '不能为空', trigger: 'blur' },
  // ],
  sation: {
    required: true,
    message: '请选择',
    trigger: 'change',
  },
  count: [
    {
      required: true,
      message: 'Please select Activity count',
      trigger: 'change',
    },
  ],
})

const changepage = (e) => {
  state.page = e
  getData()
}



const getData = async () => {
  let res = await proxy.$api.home.userPage(
    {
      limit: 10,
      page: state.page,
      username: state.params.realName,
      roleId: state.params.roleId,
    })
  state.tableData = res.data.list
  state.totalPage = res.data.total
  console.log('res', res);
}
getData(state.page)
const getSelect = async () => {
  let res = await proxy.$api.home.roleList()
  state.options = res.data
}
getSelect()
const search = () => {
  console.log('state', state.params);
  state.params.startDate = state.params.time[0]
  state.params.endDate = state.params.time[1]
  getData(state.page)
}
const reast = () => {
  state.params = {
    monthStatus: '',
    realName: '',
    time: ['', ''],
    startDate: '',
    endDate: '',
  }
  getData(state.page)
}
const update = (row) => {
  state.dialogVisible = true
  proxy.$api.home.userDetail(row.id).then(res => {
    console.log('res', res);
    ruleForm.username = res.data.username
    ruleForm.realName = res.data.realName
    ruleForm.mobile = res.data.mobile
    ruleForm.id = res.data.id
    ruleForm.password = res.data.password
    ruleForm.region = res.data.roleIdList[0]
    res.data.status === 1 ? ruleForm.sation = true : ruleForm.sation = false
  })
  state.row = row
}

const addmore = () => {
  state.dialogVisible = true
}

const Deletet = async (row) => {
  ElMessageBox.confirm('是否此角色？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'mis-msg-prompt'
  })
    .then(() => {
      proxy.$api.home.userDelet([row.id]).then(() => {
        ElMessage.success('删除成功!')
        getData()
      })
    })
    .catch(() => { })
}


const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!', ruleForm)
      ruleForm.roleIdList[0] = ruleForm.region
      ruleForm.sation === true ? ruleForm.status = 1 : ruleForm.status = 0
      console.log('ruleForm.id !=', ruleForm.id != '');
      if (ruleForm.id) {
        proxy.$api.home.userput(ruleForm).then(res => {
          console.log('res', res)
          if (res.msg === 'success') {
            ElMessage.success('修改成功!')
            state.dialogVisible = false
            resetForm()
            getData()
          }
        })
      } else {
        proxy.$api.home.userSave(ruleForm).then(res => {
          console.log('res', res)
          if (res.msg === 'success') {
            ElMessage.success('添加成功!')
            state.dialogVisible = false
            resetForm()
            getData()
          }
        })
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
  setTimeout(() => {
    state.dialogVisible = false
  }, 200);
}
</script>

<style lang="scss" scoped>
.configuredRule {
  padding: 20px;

  .search_detail {
    display: flex;

    .search {
      margin-right: 10px;
      display: flex;
      align-items: center;

      .span_name {
        width: 110px;
        font-size: 16px;
      }
    }
  }

  .card-main {
    margin-top: 20px;
    height: calc(100vh - 200px);
    position: relative;

    .pagination {
      margin-top: 10px;
      display: flex;
      justify-content: flex-end;
      text-align: right;
    }
  }
}

:deep(.el-calendar__body) {
  height: 100%;
}

:deep(.el-calendar-table) {
  height: 100%;
}

:deep(.el-calendar-day) {
  height: 100%;
}

.drawer-content {
  h3 {
    font-size: 28px;
  }

  .block3 {
    display: flex;
    align-items: center;
    margin-top: 5px;

    .span-txt1 {
      font-size: 16px;
      min-width: 90px;
      color: #555;
    }
  }

  .blcok2 {
    position: relative;
    border: 1px solid #ccc;
    padding: 10px;
    margin: 5px 0px;
    border-radius: 10px;

    .button {
      position: absolute;
      right: 10px;
      bottom: 4px;
    }
  }
}
</style>